from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import argparse
import yaml
import logging
from src import const
from src.google_tile import download_tiles_all_count
from src.geo_func import circle2tiles
from src.geo_classes import Circle, Node
import numpy as np
import pandas as pd

sys.path.append('./src')
from src.inference import MyModel


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--conf', help="conf file", default="conf/server.yml", type=argparse.FileType('r'))
    parser.add_argument('--circle_info', help="代表商圈的csv，保证每行的前3个是lat、lng、r。第一行是标题", default="data/sourceB/shanghai_mall.csv")
    parser.add_argument('--china-convert', type=bool, default=True)
    parser.add_argument('--dir', default='data/tiles')
    parser.add_argument('--save-file', default='data/sourceA/pic_shanghai_mall.txt')
    parser.add_argument('--num-classes', default=6, type=int)
    return parser.parse_args()


def gen_feature(circle, model, args):
    tiles = circle2tiles(circle, args.china_convert)
    downloaded_num = download_tiles_all_count(tiles, args.dir)
    all_num = len(tiles)
    if downloaded_num / all_num < 0.8:
        logging.warning('Pic number is not enough for this region!')
        return None
    else:
        n_file = 0
        feature = np.array([0.0] * args.num_classes)
        for tile in tiles:
            filename = '%d_%d_%d.jpg' % (tile[0], tile[1], tile[2])
            filename = os.path.join(args.dir, filename)
            if os.path.exists(filename):
                one_feature, _ = model.detect_one_img(filename)
                feature += one_feature
                n_file += 1
        return (feature / n_file)


def main(args):
    conf = yaml.load(args.conf)
    model = MyModel(conf, ext='jpg')
    # with open(conf['label_file']) as f:
    #     print(f.read())
    save_file = open(args.save_file, 'w')
    circle_info = pd.read_csv(args.circle_info, index_col=0)
    all_count = 0
    has_enough_img = 0
    for row in circle_info.itertuples():
        all_count += 1
        one_circle = Circle(Node(lat=row.lat, lng=row.lng), row.r)
        logging.info("no." + str(all_count) + "  " + str(one_circle))
        feature = gen_feature(one_circle, model, args)
        if feature is not None:
            has_enough_img += 1
            save_file.write('%f %f %d' % (row.lat, row.lng, row.r))
            for x in feature:
                save_file.write(' %f' % x)
            logging.info(feature)
            save_file.write('\n')
            save_file.flush()
    save_file.close()
    print("all circles: ", all_count, "has enough img: ", has_enough_img)

if __name__ == '__main__':
    args = parse_args()
    logging.basicConfig(level=logging.INFO)
    print(main(args))
